package com.kaiwukj.android.ufamily.mvp.ui.page.home;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.hyphenate.chat.EMClient;
import com.kaiwukj.android.mcas.integration.AppManager;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.app.constant.EventCode;
import com.kaiwukj.android.ufamily.mvp.helper.AppStore;
import com.kaiwukj.android.ufamily.mvp.http.entity.base.EventMessage;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.KaiwuEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.TokenInvalidEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.UpdateUserInfoEvent;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.HomeContainerL1Fragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.keeper.KeeperContainerFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.mall.MallContainerFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.mine.MineFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.service.ServiceFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.mine.house.door.ZghlVideoActivity;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.zghl.mclient.client.MQTTConstants;
import com.zghl.mclient.client.ZghlMClient;
import com.zghl.mclient.client.ZghlMqttListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.yokeyword.fragmentation.ISupportFragment;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.MainRouterUrl;

@Route(path = MainRouterUrl)
public class MainActivity extends BaseActivity {
    @BindView(R.id.bnve_main_bottom_navigation)
    BottomNavigationView mMainBottomBnve;

    // @Inject
    //RxPermissions mRxPermissions;
    @Autowired(name = "EXTRA_KEY_REFRESH")
    boolean isLoginRefresh;

    private long backMs = 0;

    private ISupportFragment[] mFragments = new ISupportFragment[5];

    private int menuId[] = {R.id.home_home_pager, R.id.home_menu_life, R.id.home_keeper, R.id.home_news, R.id.home_mine};

    private int currentPage = 0;


    @Override
    public void initData(Bundle savedInstanceState) {
        initWidget();
        //requestPermissions();
        mMainBottomBnve.setItemIconTintList(null);
        buildBottomMenuListener();
        //assert mPresenter != null;
        // new Handler().postDelayed(() -> mPresenter.requestVersionUpdate(), 6 * 1000);
        //mPresenter.requestVersionUpdate();

        try {
            registerZghlMQTT();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void registerZghlMQTT() {
        ZghlMqttListener zghlMqttListener = new ZghlMqttListener() {
            @Override
            public void onReceiveMessage(String type, String msg) {
                LogUtils.d("onReceiveMessage---------------->" + msg + ":" + type);
                switch (type) {
                    case MQTTConstants.FRESH:
                        // isRefresh = true;
                        //该消息为 电脑端 通过申请钥匙的审核时服务器主动发送至app的消息，通知app刷新首页数据
                        // getAllData(false);
                        break;
                    case MQTTConstants.OPEN_DOOR_SUCCESS:
                        // 开门成功消息， msg 开门成功的门禁机 的guid（同时也是钥匙的guid）
                        EventBus.getDefault().post(new KaiwuEvent<>(0, EventCode.EVENT_OPEN_DOOR, msg));
                        break;
                    case MQTTConstants.CALL_UP:
                        // 门禁机发来 视频通话请求
                        Intent intent = new Intent(MainActivity.this.getApplicationContext(), ZghlVideoActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        break;
                    case MQTTConstants.HANG_UP:
                        //门禁机主动挂断电话
                        EventBus.getDefault().post(new KaiwuEvent<String>(0, EventCode.EVENT_HANG_UP, msg));
                        break;
                    case MQTTConstants.NEED_RELOGIN:
                        // 因单点登录，若在其他设备上登录后，仍在本设备进行操作，会收到该指令,需要提示用户重新登录
                        // 部分token过期，也会回调该 type
                        //showMessage(msg);
                        int appVersionCode = AppUtils.getAppVersionCode();
                        //LSSpUtil.put(SPConstants.SP_VERSION_CODE, appVersionCode);
                        //startAct(LoginActivity.class);
                        showMessage("门禁验证失效，请尝试重新登录");

                        EventBus.getDefault().postSticky(new TokenInvalidEvent());
                        break;
                    default:
                        showMessage(msg);
                        break;
                }
            }

            @Override
            public void onConnectionStateChange(boolean b, String s) {
                LogUtils.d("onConnectionStateChange---------------->" + b + ":" + s);
            }

        };

        ZghlMClient.getInstance().setMqttListener(zghlMqttListener);


        /*
        ZghlMClient.getInstance().autoOauthorization(new ZghlStateListener() {
            @Override
            public void onSuccess(int i, String s) {

            }

            @Override
            public void onError(int i, String s) {

            }
        });*/
    }

    @Override
    protected int getLayoutId() {
        QMUIStatusBarHelper.translucent(this);
        ARouter.getInstance().inject(this);
        return R.layout.activity_main;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        initFragment();
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
        //LogUtils.d("notification---------------------->" + notificationManagerCompat.areNotificationsEnabled());
        if (!notificationManagerCompat.areNotificationsEnabled()) {
            subscribe(Observable.timer(5000, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aLong ->
                            openSettingActivity(this,
                                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                    "开启通知获取更优质的服务体验")));
        }
    }

    @Override
    public boolean useFragment() {
        return true;
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        // ZghlMClient.startService();
    }

    private void buildBottomMenuListener() {
        mMainBottomBnve.setOnNavigationItemSelectedListener(menuItem -> {
            switch (menuItem.getItemId()) {
                case R.id.home_home_pager:
                    currentPage = 0;
                    showHideFragment(mFragments[0]);
                    break;
                case R.id.home_menu_life:
                    currentPage = 1;
                    showHideFragment(mFragments[1]);
                    break;
//                    管家
   /*             case R.id.home_menu_open_door:
                    showHideFragment(mFragments[2]);
//                    this.miDoor = menuItem;
//                    menuItem.setEnabled(false);
//                    mPresenter.requestServiceList();
                    break;*/
                case R.id.home_keeper:
                    // currentPage = 2;
                    //  showHideFragment(mFragments[2]);
                    if (getApp().getUserInfo().getHkeeperId() < 0) {
                        //if(true){
                        ARouter.getInstance().build(ARouterUrlKt.MineKeeperContainerUrl).navigation();
                    } else {
                        ARouter.getInstance().build(ARouterUrlKt.KeeperIndexUrl)
                                .navigation();
                    }
                    // ARouter.getInstance().build(ARouterUrlKt.MineKeeperContainerUrl).navigation();
                    break;
                case R.id.home_news:
                    currentPage = 3;
                    showHideFragment(mFragments[3]);
                    break;
                case R.id.home_mine:
                    if (currentPage == 4) {
                        EventBus.getDefault().post(new UpdateUserInfoEvent());
                    }
                    currentPage = 4;
                    showHideFragment(mFragments[4]);
                    break;
            }
            return true;
        });
    }


    /**
     * 初始化任务
     */
    public void initWidget() {
        //判断token
        String token = AppStore.getToken();
        if (token == null) {
            ARouter.getInstance().build(ARouterUrlKt.CodeLoginRouterUrl).navigation(this, new NavigationCallback() {
                @Override
                public void onFound(Postcard postcard) {

                }

                @Override
                public void onLost(Postcard postcard) {

                }

                @Override
                public void onArrival(Postcard postcard) {
                    finish();
                }

                @Override
                public void onInterrupt(Postcard postcard) {

                }
            });
        }

        //mMainBottomBnve.enableAnimation(false);
        // mMainBottomBnve.enableShiftingMode(false);
    }

   /* @Override
    public void showLoading() {
        miDoor.setEnabled(true);
    }*/

    /*@Override
    public void killMyself() {
        finish();
    }*/
    private void initFragment() {
        //mFragments[0] = HomeFragment.Companion.newInstance(isLoginRefresh);
        mFragments[0] = new HomeContainerL1Fragment();
        mFragments[1] = ServiceFragment.newInstance();
        // mFragments[2] = (ISupportFragment) ARouter.getInstance().build(ARouterUrlKt.FavShopMainUrl).navigation();
        mFragments[2] = KeeperContainerFragment.newInstance(!StringUtils.isEmpty(getApp().getUserInfo().getKeeperHxName()));
        mFragments[3] = MallContainerFragment.newInstance();
        //mFragments[3] = ManagerFragment.newInstance();
        // mFragments[3] = ShopFragment.newInstance();
        mFragments[4] = MineFragment.newInstance();
        loadMultipleRootFragment(R.id.fl_main_container, 0, mFragments);

        //  setUnReadChatMsg(EMClient.getInstance().chatManager().getUnreadMessageCount());
    }

    /*@Override
    public AppCompatActivity getActivity() {
        return this;
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // this.mRxPermissions = null;
        //ZghlMClient.getInstance().setMqttListener(null);
    }
/*
    @Override
    public void getDeviceList(@NotNull MyDeviceListResult data) {
        elementData = data.getUnitList();
        communityData = data.getCdList();
        roomData = data.getRoomList();
        popupWindowUtil.createGateDialog(getActivity(), communityData, elementData, roomData).showBottom(R.layout.activity_main);
    }*/

    @Subscribe
    public void onMaintEvent(String message) {
        //切换到生活
        if (StringUtils.isEmpty(message)) {
            showHideFragment(mFragments[1]);
            mMainBottomBnve.setSelectedItemId(menuId[1]);
//            mMainBottomBnve.setCurrentItem(1);
        }
    }


    @Subscribe
    public void onMainEvent(EventMessage message) {
        //切换到生活
        if (message.getMsg().equals("打电话")) {
            PopupWindowUtil.createCallDialog(this, Constant.BUS_PHONE).showCenter(R.layout.activity_join);
        }
        if (message.getMsg().equals("neighbor")) {
            showHideFragment(mFragments[2]);
            //  mMainBottomBnve.setCurrentItem(2);
            mMainBottomBnve.setSelectedItemId(menuId[2]);
            EventBus.getDefault().post("notify01");
        }
        if (message.getMsg().equals("neighbor-msg")) {
            showHideFragment(mFragments[2]);
            // mMainBottomBnve.setCurrentItem(2);
            mMainBottomBnve.setSelectedItemId(menuId[2]);
            //  ((ChatMessageFragment) mFragments[2]).setPage(2);
            //EventBus.getDefault().postSticky("notify");
        }
        if (message.getMsg().equals("chat_count")) {
            setUnReadChatMsg(EMClient.getInstance().chatManager().getUnreadMessageCount());
        }
    }


    /*@Override
    public void onVersionUpdateResult(@NotNull VersionUpdateResult result) {
        assert mPresenter != null;
        int currentVersion = mPresenter.getAppVersionCode();
        if (currentVersion < result.getVersionId()) {
            //TODO 需要更新

        }
    }*/

    private void setUnReadChatMsg(int count) {
        //  count = 12;
        BadgeDrawable badgeDrawable = mMainBottomBnve.getOrCreateBadge(menuId[2]);
        badgeDrawable.setBounds(0, 0, SizeUtils.dp2px(12), SizeUtils.dp2px(12));
        badgeDrawable.setVerticalOffset(SizeUtils.dp2px(6));
        badgeDrawable.setBackgroundColor(ContextCompat.getColor(this, R.color.app_color_theme));
        badgeDrawable.setMaxCharacterCount(99);
        if (count <= 0) {
            badgeDrawable.setVisible(false);
            badgeDrawable.clearNumber();
        } else {
            badgeDrawable.setVisible(true);
            badgeDrawable.setNumber(count);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        boolean exit = intent.getBooleanExtra("exit", false);
        if (exit) {
            finish();
            AppManager.getAppManager().killAll();
        }
    }

    @Override
    public void onBackPressedSupport() {
        //super.onBackPressedSupport();
        if (System.currentTimeMillis() - backMs > (3 * 1000)) {
            backMs = System.currentTimeMillis();
            ToastUtils.showShort("再次点击退出应用");
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("exit", true);
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTopFragment().onFragmentResult(requestCode, resultCode, data != null ? data.getExtras() : null);
    }

}
